package com.hongshan.wallet.widget

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import com.hongshan.wallet.base.BaseRecyclerAdapter

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.hongshan.wallet.widget
 * @author   : zhangxx
 * @date     : 2019/4/23
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */

class EmptyRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
    RecyclerView(context, attrs, defStyle) {

    private val observer = object : RecyclerView.AdapterDataObserver() {
        override fun onChanged() {
            checkIfEmpty()
        }

        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            checkIfEmpty()
        }

        override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
            checkIfEmpty()
        }
    }

    private fun checkIfEmpty() {
        if (adapter is BaseRecyclerAdapter) {
            val baseAdapter = adapter as BaseRecyclerAdapter?
            if (baseAdapter?.isEmpty() == true) {
                baseAdapter.showEmpty()
            } else{
                baseAdapter?.hideEmpty()
            }
        }
    }

    override fun setAdapter(adapter: Adapter<*>?) {
        val oldAdapter = getAdapter()
        oldAdapter?.unregisterAdapterDataObserver(observer)
        super.setAdapter(adapter)
        adapter?.registerAdapterDataObserver(observer)
        checkIfEmpty()
    }

}